package cn.chenli.job.common.controller;

import pro.tools.data.text.ToolJson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author chenli
 * @create 2017-08-11
 */
public class Controller {
    public HttpServletRequest request;
    public HttpServletResponse response;
    public String viewPath;
    private static final String contentType = "application/json; charset=UTF-8";
    private static final String contentTypeForIE = "text/html; charset=UTF-8";
    private boolean forIE = false;

    public HttpServletRequest getRequest() {
        return request;
    }

    public Controller setRequest(HttpServletRequest request) {
        this.request = request;
        return this;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public Controller setResponse(HttpServletResponse response) {
        this.response = response;
        return this;
    }

    Controller setRequestResponse(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
        return this;
    }

    Controller setParams(HttpServletRequest request, HttpServletResponse response,String viewPath){
        this.request = request;
        this.response = response;
        this.viewPath = viewPath;
        return this;
    }

    /**
     * 返回json数据
     */
    public void returnJson(Object o){
        PrintWriter writer = null;
        try {
            response.setHeader("Pragma", "no-cache");	// HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            response.setContentType(forIE ? contentTypeForIE : contentType);
            writer = response.getWriter();
            writer.write(ToolJson.modelToJson(o));
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 返回jsp
     * @param view:返回的y
     */
    public void returnView(String view){
        try {
            request.getRequestDispatcher(viewPath + view).forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //没用
    public void returnHtml(){
        try {
            request.getRequestDispatcher("/WEB-INF/page/test1.html").forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }
}